<?php

namespace app\admin\controller\store;

use app\admin\model\store\GoodsSku;
use app\common\controller\AdminController;
use app\common\service\lib\UploadFile;
use app\common\service\store\GoodsService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use app\admin\model\store\Goods as GoodsModel;
use think\App;
use think\Request;

/**
 * @ControllerAnnotation(title="goods")
 */
class Goods extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\store\Goods();

        $this->assign('getIsPostageList', $this->model->getIsPostageList());

        $this->assign('getIsRecommendList', $this->model->getIsRecommendList());

        $this->assign('getIsDelList', $this->model->getIsDelList());

        $this->assign('getIsHotList', $this->model->getIsHotList());

        $this->assign('getIsNewList', $this->model->getIsNewList());

        $this->assign('getIsQualityList', $this->model->getIsQualityList());

        $this->assign('getIsStatusList', $this->model->getIsStatusList());

        $this->assign('getIsSpecificaList', $this->model->getIsSpecificaList());

    }

    /**
     * Author:Zhongyuan Lu
     * 商品列表展示
     * @return mixed|\think\response\Json
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit,$where) = $this->buildTableParames();
            $isDelete = 0;
            $status = $this->request->get('keyword', 1);

            switch ($status) {
                case 1:
                    $where[] = [
                        ['is_status', '=', 1],
                        ['goods_stock', '<>', 0]
                    ];
                    break;
                case 2:
                    $where[] = ['is_status', '=', 0];
                    break;
                case 3:
                    $where[] = ['goods_stock', '=', 0];
                    break;
                case 4:
                    $isDelete = 1;
                    break;
                default:
                    break;
            }

            $data = GoodsService::getGoodsList($page, $limit, $where, $isDelete);

            return json($data);
        }
        return $this->fetch();
    }

    /**
     * Author:Zhongyuan Lu
     * 获取出售中的商品
     * @return array|mixed
     * @throws \think\db\exception\DbException
     */
    public function selectGoods()
    {
        if ($this->request->isAjax()){
            $page = $this->request->get('page',$this->page);
            $pagesize = $this->request->get('limit',$this->pagesize);
            $goods_name = $this->request->get('goods_name');
            if ($goods_name) {
                $where[] = ['goods_name', 'like', "$goods_name%"];
            }
            //上架中  有库存的商品
            $where[] = [
                ['
                is_status', '=', 1],
                ['goods_stock', '<>', 0]
            ];
            return GoodsService::getGoodsList($page,$pagesize,$where);
        }
        return $this->fetch();
    }

    public function selectGoodsSku()
    {
        $goods_id = $this->request->get('goods_id');
        if ($this->request->isAjax()){
            $page = $this->request->get('page',$this->page);
            $pagesize = $this->request->get('limit',$this->pagesize);
            //上架中  有库存的商品
            $type = 2; //2 返回layui动态表格需要数据

            return GoodsService::getGoodsSku($goods_id,$type,$page,$pagesize);

        }
        $this->assign('goods_id',$goods_id);
        return $this->fetch();
    }

    /**
     * Author:Zhongyuan Lu
     * 恢复商品
     * @return \think\response\Json|void
     */
    public function restore()
    {
        $id = $this->request->get('id', 0, 'int');
        if (empty($id) || $id < 1) {
            return $this->error('参数错误');
        }

        $data = GoodsService::restore($id);
        return json($data);
    }

    /**
     * Author:Zhongyuan Lu
     * 真实删除
     * @return \think\response\Json|void
     */
    public function forceDelete()
    {
        $id = $this->request->get('id', 0, 'int');
        if (empty($id) || $id < 1) {
            return $this->error('参数错误');
        }

        $data = GoodsService::forceDelete($id);
        return json($data);
    }

    public function getCate()
    {
        $data = GoodsService::getTreeCate();
        return json($data);
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'goods_name' => 'require',
                'goods_desc' => 'require',
                'image' => 'require',
                'goods_carousel' => 'require',
                'goods_price' => 'require',
                'goods_cost_price' => 'require',
            ];
            $this->validate($post, $rule);

            $save = GoodsService::goodsSave($post);
            $save['code'] ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = GoodsService::getSku($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'goods_name' => 'require',
                'goods_desc' => 'require',
                'image' => 'require',
                'goods_carousel' => 'require',
                'goods_price' => 'require',
                'goods_cost_price' => 'require',
            ];
            $this->validate($post, $rule);
//            try {
//                $save = GoodsService::goodsUpdate($row, $post);
//            } catch (\Exception $e) {
//                $this->error('保存失败');
//            }
//            $save ? $this->success('保存成功') : $this->error('保存失败');
            $this->success('保存成功');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    public function list()
    {
        $data = GoodsModel::field(['id', 'goods_name'])->select();
        $data && $data = $data->toArray();
        return json(['code' => 1, 'msg' => null, 'data' => $data]);
    }

    public function upFile()
    {
        $file = $this->request->file('file')->getPathName();

        $path = UploadFile::upFile($file);

        return json(['url' => $path]);
    }

    public function ruleList($id = 0)
    {
        $data = GoodsService::getRuleList($id);
        foreach ($data as &$v) {
            $v['specifica_value'] = json_decode($v['specifica_value'], true);
        }
        unset($v);
        return json(['code' => 1, 'msg' => null, 'data' => $data]);
    }

    public function mark($arr)
    {
         for ($i =0;$i<count($arr);$i++){
             while (count($arr[$i]) > 1){

             }
         }
    }

    public function  matchusers($thisroomusers) {
        $length = count($thisroomusers);
        $result = ['userid' => 0, 'touserid' => 0, 'diff' => PHP_INT_MAX];
        for ($i=0; $i<$length; ++$i) {
            for ($j=$i+1; $j<$length; ++$j) {
                $diff = abs($thisroomusers[$i]['lev'] - $thisroomusers[$j]['lev']);
                if ($diff < $result['diff']) {
                    $result['userid'] = $thisroomusers[$i]['userid'];
                    $result['touserid'] = $thisroomusers[$j]['userid'];
                    $result['diff'] = $diff;
                }
            }
        }
        return $result;
    }


    public function upload()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post();
            $file = $_FILES['file'];
//            $file = sprintf('tmp/%s.%s',$_POST['fileName'],$_POST['fileExt']);
            $res = GoodsService::bigUpload($params, $file);
            return json($res);
        }
        return $this->fetch();
    }

    /**
     * Author:Xinpeng Yang
     * 根据skuid获取详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function skuById(Request $request)
    {
        $goods_id = $request->get('goods_id');
        $data = GoodsService::getGoodsSku($goods_id);
        return json($data);
    }

    /**
     * Author:Yingbo Sun
     * 获取商品
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function goodsId(Request $request)
    {
        $goodsId = $request->get('goods_id');
        $data = GoodsModel::where('id',$goodsId)->find();
        $data && $data = $data->toArray();
        return json($data);
    }




    /**
     * Author:Zhongyuan Lu
     * 根据skuid获取详情
     * @return array|\think\Model|null
     */
    public function getSkuDetail()
    {
        $skuId = $this->request->get('skuId');
        if (is_array($skuId)) {
            $skuId = $skuId[0];
        }
        if (strpos($skuId,',')) {
            $skuId = substr($skuId,0,strpos($skuId,','));
        }
        return GoodsService::getSkuDetail($skuId);
    }
}